<template>
  <div class="scheme-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>分发方案管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增分发方案
          </el-button>
        </div>
      </template>

      <el-table :data="schemeList" style="width: 100%" v-loading="loading">
        <el-table-column prop="schemeName" label="方案名称" width="150" />
        <el-table-column prop="schemeCode" label="方案编码" width="120" />
        <el-table-column prop="upstreamChannels" label="上游渠道" width="200">
          <template #default="{ row }">
            <el-tag v-for="channel in row.upstreamChannels" :key="channel" size="small" style="margin-right: 5px">
              {{ getChannelName(channel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="downstreamChannels" label="下游渠道" width="200">
          <template #default="{ row }">
            <el-tag v-for="channel in row.downstreamChannels" :key="channel" size="small" style="margin-right: 5px">
              {{ getChannelName(channel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="rules" label="分发规则" width="100">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewRules(row)">
              查看规则 ({{ row.rules.length }})
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button 
              :type="row.status === 1 ? 'danger' : 'success'" 
              link 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pageInfo.pageNum"
        v-model:page-size="pageInfo.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑分发方案对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="handleDialogClose"
    >
      <el-form
        ref="schemeFormRef"
        :model="schemeForm"
        :rules="schemeRules"
        label-width="100px"
      >
        <el-form-item label="方案名称" prop="schemeName">
          <el-input v-model="schemeForm.schemeName" placeholder="请输入方案名称" />
        </el-form-item>
        <el-form-item label="方案编码" prop="schemeCode">
          <el-input v-model="schemeForm.schemeCode" placeholder="请输入方案编码" />
        </el-form-item>
        <el-form-item label="上游渠道" prop="upstreamChannels">
          <el-select 
            v-model="schemeForm.upstreamChannels" 
            multiple 
            placeholder="请选择上游渠道"
            style="width: 100%"
          >
            <el-option 
              v-for="channel in upstreamChannelOptions" 
              :key="channel.channelCode" 
              :label="channel.channelName" 
              :value="channel.channelCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="下游渠道" prop="downstreamChannels">
          <el-select 
            v-model="schemeForm.downstreamChannels" 
            multiple 
            placeholder="请选择下游渠道"
            style="width: 100%"
          >
            <el-option 
              v-for="channel in downstreamChannelOptions" 
              :key="channel.channelCode" 
              :label="channel.channelName" 
              :value="channel.channelCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="schemeForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="schemeForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入方案描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 分发规则查看对话框 -->
    <el-dialog
      v-model="rulesDialogVisible"
      title="分发规则"
      width="600px"
    >
      <el-table :data="currentRules" style="width: 100%">
        <el-table-column prop="ruleName" label="规则名称" width="150" />
        <el-table-column prop="ruleType" label="规则类型" width="120">
          <template #default="{ row }">
            {{ getRuleTypeText(row.ruleType) }}
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
      </el-table>
      <template #footer>
        <el-button @click="rulesDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { getSchemeList, createScheme, updateScheme, deleteScheme, updateSchemeStatus } from '@/api/distribution'
import { getChannelList } from '@/api/channel'
import type { DistributionScheme, ChannelSource, DistributionRule } from '@/types/api'

const loading = ref(false)
const schemeList = ref<DistributionScheme[]>([])
const total = ref(0)
const upstreamChannelOptions = ref<ChannelSource[]>([])
const downstreamChannelOptions = ref<ChannelSource[]>([])

const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10
})

const dialogVisible = ref(false)
const rulesDialogVisible = ref(false)
const submitLoading = ref(false)
const schemeFormRef = ref<FormInstance>()

const schemeForm = reactive({
  id: undefined as number | undefined,
  schemeName: '',
  schemeCode: '',
  upstreamChannels: [] as string[],
  downstreamChannels: [] as string[],
  status: 1,
  description: ''
})

const schemeRules: FormRules = {
  schemeName: [{ required: true, message: '请输入方案名称', trigger: 'blur' }],
  schemeCode: [{ required: true, message: '请输入方案编码', trigger: 'blur' }],
  upstreamChannels: [{ required: true, message: '请选择上游渠道', trigger: 'change' }],
  downstreamChannels: [{ required: true, message: '请选择下游渠道', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const currentRules = ref<DistributionRule[]>([])

const dialogTitle = computed(() => 
  schemeForm.id ? '编辑分发方案' : '新增分发方案'
)

const getChannelName = (channelCode: string) => {
  const allChannels = [...upstreamChannelOptions.value, ...downstreamChannelOptions.value]
  const channel = allChannels.find(c => c.channelCode === channelCode)
  return channel ? channel.channelName : channelCode
}

const getRuleTypeText = (ruleType: string) => {
  const textMap: Record<string, string> = {
    'GEOGRAPHIC': '地域规则',
    'PRODUCT_TYPE': '产品类型',
    'CUSTOMER_PROFILE': '客户画像',
    'TIME': '时间规则',
    'PRIORITY': '优先级规则',
    'ROUND_ROBIN': '轮询规则',
    'PROPORTION': '比例规则'
  }
  return textMap[ruleType] || ruleType
}

const fetchSchemeList = async () => {
  loading.value = true
  try {
    const response = await getSchemeList(pageInfo)
    schemeList.value = response.records
    total.value = response.total
  } catch (error) {
    ElMessage.error('获取分发方案列表失败')
  } finally {
    loading.value = false
  }
}

const fetchChannelOptions = async () => {
  try {
    const [upstreamResponse, downstreamResponse] = await Promise.all([
      getChannelList({ pageNum: 1, pageSize: 100, channelDirection: 'UPSTREAM' }),
      getChannelList({ pageNum: 1, pageSize: 100, channelDirection: 'DOWNSTREAM' })
    ])
    
    upstreamChannelOptions.value = upstreamResponse.records
    downstreamChannelOptions.value = downstreamResponse.records
  } catch (error) {
    ElMessage.error('获取渠道选项失败')
  }
}

const handleAdd = () => {
  schemeForm.id = undefined
  schemeForm.schemeName = ''
  schemeForm.schemeCode = ''
  schemeForm.upstreamChannels = []
  schemeForm.downstreamChannels = []
  schemeForm.status = 1
  schemeForm.description = ''
  dialogVisible.value = true
}

const handleEdit = (row: DistributionScheme) => {
  schemeForm.id = row.id
  schemeForm.schemeName = row.schemeName
  schemeForm.schemeCode = row.schemeCode
  schemeForm.upstreamChannels = [...row.upstreamChannels]
  schemeForm.downstreamChannels = [...row.downstreamChannels]
  schemeForm.status = row.status
  schemeForm.description = row.description || ''
  dialogVisible.value = true
}

const handleViewRules = (row: DistributionScheme) => {
  currentRules.value = row.rules
  rulesDialogVisible.value = true
}

const handleToggleStatus = async (row: DistributionScheme) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '禁用' : '启用'}方案"${row.schemeName}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await updateSchemeStatus(row.id, row.status === 1 ? 0 : 1)
    ElMessage.success(`${row.status === 1 ? '禁用' : '启用'}成功`)
    fetchSchemeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleDelete = async (row: DistributionScheme) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除方案"${row.schemeName}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await deleteScheme(row.id)
    ElMessage.success('删除成功')
    fetchSchemeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!schemeFormRef.value) return
  
  try {
    await schemeFormRef.value.validate()
    submitLoading.value = true
    
    if (schemeForm.id) {
      await updateScheme(schemeForm.id, schemeForm)
      ElMessage.success('更新成功')
    } else {
      await createScheme(schemeForm)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchSchemeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  schemeFormRef.value?.resetFields()
}

const handleSizeChange = (val: number) => {
  pageInfo.pageSize = val
  fetchSchemeList()
}

const handleCurrentChange = (val: number) => {
  pageInfo.pageNum = val
  fetchSchemeList()
}

onMounted(() => {
  fetchSchemeList()
  fetchChannelOptions()
})
</script>

<style scoped>
.scheme-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>